﻿if (typeof (Seq) == 'undefined') Seq = new Object();

if (typeof (Seq.Notifications) == 'undefined') Seq.Notifications = new Object();

Seq.Notifications._handlers = {};

Seq.Notifications.Observe = function(id, callback) {
	if (Seq.Notifications._handlers[id])
		Seq.Notifications._handlers[id].push(callback);
	else
		Seq.Notifications._handlers[id] = [callback];
}

Seq.Notifications.FireHandlers = function(id, metadata) {
	console.log('fire handlers: id=' + id + ', metadata=' + metadata);
	if (Seq.Notifications._handlers[id]) {
		for (var k = 0; k < Seq.Notifications._handlers[id].length; k++) {
			Seq.Notifications._handlers[id][k](id, metadata);
		}
	}
}

Seq.Notifications._onPollData = function(r) {
	var cmd = r.responseText.split('|');
	// console.log(cmd);
	if (cmd.length > 0) {
		if (cmd[0] != '') {
			var args = cmd;
			args.splice(0, 1);
			Seq.Notifications.FireHandlers(cmd[0], args);
		}
	}
	setTimeout("Seq.Notifications._PollOnce();", 100);
}

Seq.Notifications._onPollError = function() {
	setTimeout("Seq.Notifications._PollOnce();", 2000);
}

Seq.Notifications._PollOnce = function() {
	var sid = Seq.State.GetCurrentSessionID();
	new Ajax.Request('/api/notifications', { method: 'get', parameters: { 'poll': sid }, onSuccess: Seq.Notifications._onPollData, onFailure: Seq.Notifications._onPollError });
}

Seq.Notifications._onNotifyData = function(r) {
	// setStatus('');
}

Seq.Notifications.Send = function(msg, extras) {
	var sid = Seq.State.GetCurrentSessionID();
	var p = { 'notify': msg, 'session': sid };
	if (extras)
		p = Object.extend(p, extras);
	new Ajax.Request('/api/call', { parameters: p, onSuccess: Seq.Notifications._onNotifyData });
}

Seq.Notifications.StartListening = function() {
	setTimeout("Seq.Notifications._PollOnce();", 500);
}





 


